using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Xml;
using Send2Sharepoint.Common;
using Send2Sharepoint.Copy;

namespace Send2Sharepoint.Repository
{
    public class Repository
    {
        private static string _userName;
        private static string _password;
        private readonly string _sharepointSiteUrl;

        public Repository()
        {
            _userName = Globals.UserName;
            _password = Globals.Password;
            _sharepointSiteUrl = Globals.SharepointSiteUrl;
        }

        public Repository(string userName, string password,string sharepointSiteServerUrl)
        {
            _userName = userName;
            _password = password;
            _sharepointSiteUrl = sharepointSiteServerUrl;
        }

        public IEnumerable<XmlNode> GetColumnsMetaData(string listName)
        {
            var listsWebService = new Lists.Lists
                                      {
                                          Url = new Uri(new Uri(_sharepointSiteUrl), "_vti_bin/Lists.asmx").ToString(),
                                          Credentials =
                                              string.IsNullOrEmpty(_userName)
                                                  ? CredentialCache.DefaultCredentials
                                                  : new NetworkCredential(_userName, _password),
                                      };
            var result = listsWebService.GetList(listName);
            listsWebService.Dispose();
            return from element in result.ChildNodes[0].ChildNodes.Cast<XmlNode>()
                    where element.Attributes["ReadOnly"] == null &&
                          (element.Attributes["FromBaseType"] == null || element.Attributes["FromBaseType"].Value == "FALSE") && 
                          !(element.Attributes["Group"] != null && element.Attributes["Group"].Value == "_Hidden")
                    select element;
        }

        public void CreateDocumentLibrary(string documentLibraryName, string description, int templateId)
        {
            var listsWebService = new Lists.Lists
                                      {
                                          Url = new Uri(new Uri(_sharepointSiteUrl), "_vti_bin/Lists.asmx").ToString(),
                                          Credentials =
                                               string.IsNullOrEmpty(_userName)
                                                   ? CredentialCache.DefaultCredentials
                                                   : new NetworkCredential(_userName, _password),
                                      };
            listsWebService.AddList(documentLibraryName, description, templateId);
            listsWebService.Dispose();
        }

        public void AddFields(string documentLibraryName,XmlNode newFields)
        {
            var listsWebService = new Lists.Lists
                                        {
                                            Url = new Uri(new Uri(_sharepointSiteUrl), "_vti_bin/Lists.asmx").ToString(),
                                            Credentials =
                                              string.IsNullOrEmpty(_userName)
                                                  ? CredentialCache.DefaultCredentials
                                                  : new NetworkCredential(_userName, _password),
                                        };
            listsWebService.UpdateList(documentLibraryName, null, newFields, null, null, null);
            listsWebService.Dispose();
        }

        public void DeleteList(string documentLibraryName)
        {
            var listsWebService = new Lists.Lists
            {
                Url = new Uri(new Uri(_sharepointSiteUrl), "_vti_bin/Lists.asmx").ToString(),
                Credentials =
                              string.IsNullOrEmpty(_userName)
                                  ? CredentialCache.DefaultCredentials
                                  : new NetworkCredential(_userName, _password),
            };
            listsWebService.DeleteList(documentLibraryName);
            listsWebService.Dispose();
        }

        public void UploadFile2007(string destinationUrl, byte[] fileData, IEnumerable<FieldInformation> metadata)
        {
            string[] destinationUrls = { Uri.EscapeUriString(destinationUrl) };
            var metadataInformation = metadata.ToArray();
            var result = new CopyResult[metadataInformation.Length];
            using (var copyWebService = new Copy.Copy{Url = new Uri(new Uri(_sharepointSiteUrl), "_vti_bin/Copy.asmx").ToString()})
            {
                copyWebService.Credentials =
                    string.IsNullOrEmpty(_userName)
                        ? CredentialCache.DefaultCredentials
                        : new NetworkCredential(_userName, _password);
                copyWebService.CopyIntoItems(destinationUrl, destinationUrls, metadataInformation, fileData, out result);
            }
            if (result[0].ErrorCode != CopyErrorCode.Success)
            {
                throw new Exception("Unable to upload");
            }
        }
    }
}